<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Models\video\BroadcasterModel;
use App\Models\video\CarouselModel;
use App\Models\video\CommonServer;
use App\Models\video\NavigationModel;
use App\Models\video\SubscribeLibraryModel;
use App\Models\video\VideoSettingModel;
use Illuminate\Http\Request;

class HomeController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['getGlobalConf', 'getBannerData','getNavigationData', 'getSign', 'getSubscribeTemplate']; //不校验openid
        parent::__construct($request);
    }

    public function getSign(){
        $settingData = VideoSettingModel::getFields("secret_id,secret_key", ["mall_id" => request()->mallData["id"]]);
        if(empty($settingData["secretId"]) || empty($settingData["secretKey"])){
            throw new \Exception("腾讯云云点播访问密钥未配置");
        }
        $secret_id = $settingData["secretId"];
        $secret_key = $settingData["secretKey"];

        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天

        // 向参数列表填入参数
        $arg_list = array(
            "secretId" => $secret_id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand());

        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $secret_key, true).$original);


        $this->returnData["data"] = ["sign" => $signature];
        return $this->return_result($this->returnData);
    }


    // 首页banner图
    public function getBannerData(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $carouselData = CarouselModel::query()->select("thumbnail_id","url","type","brief")->where([
            ["mall_id", "=", $request->mallData["id"]], ["start_time", "<=", time()], ["end_time", ">=", time()]
        ])->orderBy("sort", "desc")->get()->toArray();
        $this->returnData["data"] = CarouselModel::transferField($carouselData);
        return $this->return_result($this->returnData);
    }

    // 获取配置信息
    public function getGlobalConf(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = VideoSettingModel::getFields(
            "operate_mode,wxapp_title,wxapp_color,carousel_status,list_show_mode,open_member,review_status,home_font_color,home_show_mode,video_show_mode,can_ios_pay",
            ["mall_id" => $request->mallData["id"]]);
        if(empty($settingData)){
            $settingData = [
                'operateMode' => '1', 'wxappTitle' => "", 'wxappColor' => '#00AAFF', 'carouselStatus' => 1, 'listShowMode' => '1', "open_member" => '0', 'reviewStatus' => '0',
                "homeFontColor" => "#909399", "homeShowMode" => "1", "videoShowMode" => "1"
            ];
        }
        $settingData["reviewStatus"] = $settingData["reviewStatus"] ? true : false;
        $settingData["CAN_IOS_PAY"] = empty($settingData["canIosPay"]) ? false : true;
        if($settingData["operateMode"] == '1'){
            $data = BroadcasterModel::getFields("list_show_mode,wxapp_color,wxapp_title,home_show_mode,video_show_mode,home_font_color", ["mall_id" => $request->mallData["id"], "status" => 1]);
            if(!empty($data)){
                $settingData = array_merge($settingData, $data);
            }
        }
        $this->returnData["data"] = $settingData;
        return $this->return_result($this->returnData);
    }

    public function getNavigationData(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if(!empty($settingData["operateMode"]) && $settingData["operateMode"] == '1'){
            $host = CommonServer::getUrl();
            $this->returnData['data'] = [
                ['path' => '/pages/index/index', 'name' => '首页', 'iconUrl' => "{$host}/uploads/home.png"],
                ['path' => '/pages/center/index/index', 'name' => '我的', 'iconUrl' => "{$host}/uploads/my.png"]
            ];
        }else{
            $data = NavigationModel::query()->select("name","path","icon_id")
                ->where(["mall_id" => $request->mallData["id"], "status" => 1])
                ->orderBy("sort", "desc")->get()->toArray();
            $this->returnData["data"] = NavigationModel::transferField($data);
        }
        return $this->return_result($this->returnData);
    }

    // 获取订阅消息模板
    public function getSubscribeTemplate(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->type){
            return $this->return_result(ErrorCode::code("params_not_exist", "模板类型"));
        }
        $type = [];
        foreach (explode(",", $request->type) as $item){
            if(!empty(SubscribeLibraryModel::$type[$item])) {
                $type[] = SubscribeLibraryModel::$type[$item];
            }
        }
        $data = SubscribeLibraryModel::query()->select("template_id")
            ->where(["mall_id" => $request->mallData["id"]])->whereIn("type", $type)
            ->get()->toArray();
        $template = [];
        foreach ($data as $item){
            $template[] = $item["template_id"];
        }
        $this->returnData["data"] = $template;
        return $this->return_result($this->returnData);
    }
}
